import React, { PureComponent } from 'react';
import { Modal, Form, Input, Slider, Select, Checkbox, Col, Row, InputNumber, Radio } from 'antd';
import { FormInstance } from 'antd/lib/form';
import style from '../base.less';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { concat, dropRight, last } from 'lodash';

const { TextArea } = Input;

interface typeForm {
  note1?: string;
  note2?: string;
  note3?: Array<number>;
  batteryRangeList?: number[]
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 16, offset: 6 },
  },
};

export default class layerLeftModel extends PureComponent {
  state = {
    isModel: false,
    confirmLoading: false,
    saveVal: {},
    title: '',
    isEV: false,//判断纯电续航里程是否显示标识 默认不显示
    batteryValues: [0, 5, 10] as (number | null)[], //电池范围
  };
  formRef = React.createRef<FormInstance>();

  handleOk = () => {
    // 提交
    this.formRef?.current?.submit();
  };
  handleCancel = () => {
    this.setState({
      isModel: false,
    });
  };
  onFinish = (val: typeForm) => {
    const { isEV } = this.state;

    const batteryValue = isEV ? this.formRef?.current?.getFieldValue('batteryRangeList') : null;

    val = { ...val, ...{ batteryRangeList: batteryValue } };

    const { onChange } = this.props;
    const { saveVal } = this.state;
    // loading
    this.setState({
      confirmLoading: true,
    });
    // 提交
    onChange({ ...saveVal, ...val }, (isModel = false) => {
      this.setState({
        isModel,
        confirmLoading: false,
      });
    });
  };
  setInitVal = (title: string = '', val: typeForm = {}) => {
    // 左侧显示的值，如果最后一个元素为100，需要去掉最后一个元素，并且如果第一个元素为0，在第一位补0
    // val.batteryRangeList 为null，两种情况：1、电动类型，但是之前未配置；2、非电动类型，不使用此字段
    const isEV = [2, 3, 4].includes(val?.engineType);
    const batteryValues = isEV ? this.processArray(val.batteryRangeList, [0, 100]) : null;
    if (isEV && !val?.batteryRangeList) {
      val = { ...val, batteryRangeList: [5, 10, 100] }
    };

    this.setState(
      {
        isModel: true,
        saveVal: val,
        confirmLoading: false,
        title,
        isEV,
        batteryValues,
      },
      () => {
        this.formRef?.current?.resetFields();
        this.formRef?.current?.setFieldsValue({ ...val });
      },
    );
  };
  typeChange = (val: any) => {
    const batteryRangeList = this.formRef?.current?.getFieldValue('batteryRangeList');
    const batteryRange = this.processArray(batteryRangeList, [0, 100]);

    const isEN = [2, 3, 4].includes(val);
    if (isEN) {
      this.formRef?.current?.setFieldValue('batteryRangeList', batteryRangeList || [5, 10, 100]);
    }
    // 当车型类别从不展示SOC的类别改变为需要展示SOC值的类别时，batteryRange是null，需要做默认填充
    if (val === 2 || val === 3 || val === 4) {
      this.setState({
        isEV: true,
        batteryValues: batteryRange,
      });
    } else {
      this.setState({
        isEV: false,
        batteryValues: null,
      });
    };
  }

  handleValueChange = (index: number, value: number | null) => {
    const newValues = [...this.state.batteryValues];
    newValues[index + 1] = value || null;
    this.setState({ batteryValues: newValues });
  };

  processArray = (arr: number[] | undefined, contant: number[]) => {
    if (!arr || arr.length === 0) {
      return [0, 5, 10];
    } else if (last(arr) === contant[1]) {
      arr = dropRight(arr);
    } else if (arr.length === 0) {
      arr = [contant[0]];
    }
    if (arr[0] !== 0) {
      arr = concat([0], arr);
    };
    return arr;
  };

  render() {
    const { isModel, confirmLoading, saveVal, title, isEV } = this.state;
    const { columns, width = 520 } = this.props;

    return (
      <Modal
        title={`${title}`}
        open={isModel}
        confirmLoading={confirmLoading}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        className={style.layerFormBox}
        width={width}
      >
        <Form
          ref={this.formRef}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          onFinish={this.onFinish}
        >
          {columns.map((e, index) => {
            let str = <div key={index}></div>;

            switch (e.type) {
              case 'input':
                str = (
                  <Form.Item {...e.formItem} key={index}>
                    <Input allowClear maxLength="20" {...e.label} />
                  </Form.Item>
                );
                break;
              case 'inputForDisplay':
                str = isEV ? (
                  <Form.Item label={e.formItem.label} required>
                    <Form.Item
                      noStyle
                      {...e.formItem} key={index}
                    >
                      <InputNumber {...e.label} precision={0} min={1} style={{ width: '200px' }} />
                    </Form.Item>
                    <span
                      className="ant-form-text"
                      style={{
                        marginLeft: 8,
                      }}
                    >
                      KM
                    </span>
                  </Form.Item>

                ) : (<div></div>);
                break;
              case 'inputNumber':
                str = (
                  <Form.Item {...e.formItem} key={index}>
                    <InputNumber {...e.label} style={{ width: '100%' }} />
                  </Form.Item>
                );
                break;

              case 'inputNumberForDisplay':
                str = isEV ? (
                  <Form.List
                    name={e.formItem.name}
                    rules={[
                      {
                        validator: async () => {
                          const battery = this.formRef.current?.getFieldValue('batteryRangeList');

                          for (let index = 0; index < battery.length - 1; index++) {
                            if (battery[index] && battery[index] >= battery[index + 1]) {
                              return Promise.reject(new Error('soc值填写异常'));
                            }
                          }
                          return Promise.resolve(); // 校验通过
                        },
                      },
                    ]}
                  >

                    {(fields, { add, remove }, { errors }) => (
                      <>
                        {fields.map((field, index) => {
                          const { batteryValues } = this.state;
                          const prevValue = batteryValues ? batteryValues[index] : null;
                          const displayValue = prevValue === null ? '-' : prevValue;
                          return (
                            <Form.Item
                              {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
                              label={index === 0 ? e.formItem.label : ''}
                              required={true}
                              key={field.key}
                              style={{ marginBottom: '0px' }}
                            >
                              <Row gutter={8} align={'bottom'} >
                                <Col span={4} offset={1}>
                                  <Form.Item>
                                    <span style={{ width: '100%' }}>{index === 0 ? '0' : displayValue}%</span>
                                  </Form.Item>
                                </Col>
                                <Col span={5}>
                                  <Form.Item>
                                    <span style={{ width: '100%' }}>&lt;&nbsp;&le;</span>
                                  </Form.Item>
                                </Col>
                                <Col span={12} >
                                  <Form.Item
                                    {...field}
                                    validateTrigger={['onBlur']}
                                    rules={e.formItem.rules}
                                  >
                                    <InputNumber
                                      min={1}
                                      max={index === fields.length - 1 ? 100 : 99}
                                      addonAfter='%'
                                      precision={0}
                                      onChange={(value: number | null) => this.handleValueChange(index, value)}
                                      disabled={index === fields.length - 1}
                                    />
                                  </Form.Item>
                                </Col>
                                <Col span={2}>
                                  <Form.Item>
                                    {index === 0 ? (
                                      fields.length < 5 && ( // 只有 fields.length < 6 时才显示新增
                                        <PlusOutlined
                                          onClick={() => {
                                            const { batteryValues } = this.state;
                                            if (fields.length === 1) {
                                              add(100, index);
                                              this.formRef?.current?.setFieldValue('batteryRangeList', [null, 100]);
                                            } else {
                                              add(undefined, fields.length - 1);
                                              const newBatteryValues = this.formRef?.current?.getFieldValue('batteryRangeList');
                                              this.formRef?.current?.setFieldValue('batteryRangeList', [...newBatteryValues]);
                                            }
                                            const newBatteryValues = [...batteryValues, null];
                                            this.setState({ batteryValues: newBatteryValues });
                                          }}
                                        />
                                      )
                                    ) : (
                                      <DeleteOutlined
                                        onClick={() => {
                                          remove(field.name);
                                          // 如果删除的是最后一条数据，把最后一条数据置为100
                                          const { batteryValues } = this.state;
                                          const newBatteryValues = [...batteryValues];
                                          if (field.name = fields.length - 1) {
                                            newBatteryValues.splice(field.name, 1); // 同步删除对应的值
                                            const newBatteryList = this.formRef?.current?.getFieldValue('batteryRangeList');
                                            newBatteryList[newBatteryList.length - 1] = 100;
                                            // 将最后一行的值设置为100
                                            this.formRef?.current?.setFieldValue('batteryRangeList', [...newBatteryList]);
                                          } else {
                                            // 如果删除的不是最后一条数据
                                            newBatteryValues.splice(field.name + 1, 1); // 同步删除对应的值
                                          }
                                          this.setState({ batteryValues: newBatteryValues });
                                        }}
                                      />
                                    )}
                                  </Form.Item>
                                </Col>
                              </Row>
                            </Form.Item>
                          )
                        })}
                        <Form.Item style={{ marginLeft: 240, marginTop: -24, marginBottom: 0 }}>
                          <Form.ErrorList errors={errors} />
                        </Form.Item>
                      </>
                    )}
                  </Form.List>
                ) : (<div></div>);
                break;

              case 'slider':
                str = (
                  <Form.Item {...e.formItem} key={index}>
                    <Slider range {...e.label} />
                  </Form.Item>
                );
                break;
              case 'textArea':
                str = (
                  <Form.Item {...e.formItem} key={index}>
                    <TextArea rows={4} maxLength="100" {...e.label} />
                  </Form.Item>
                );
                break;
              case 'select':
                str = (
                  <Form.Item {...e.formItem} key={index}>
                    <Select {...e.label} options={e.options}>
                      {/* {e.options?.map((x:any) => (
                        <Option value={x.value} key={x.value}>
                          {x.label}
                        </Option>
                      ))} */}
                    </Select>
                  </Form.Item>
                );
                break;
              case 'selectForDisplay':
                str = (
                  <Form.Item {...e.formItem} key={index}>
                    <Select {...e.label} options={e.options} onChange={this.typeChange}>
                    </Select>
                  </Form.Item>
                );
                break;
              case 'checkbox':
                str = (
                  <Form.Item {...e.formItem} key={index}>
                    <Checkbox.Group {...e.label} style={{ width: '100%' }}>
                      <Row>
                        {e.options?.map(x => (
                          <Col span={8} key={x.value}>
                            <Checkbox value={x.value}>{x.label}</Checkbox>
                          </Col>
                        ))}
                      </Row>
                    </Checkbox.Group>
                  </Form.Item>
                );
                break;
              case 'radio':
                str = (
                  <Form.Item {...e.formItem} key={index}>
                    <Radio.Group  {...e.label} options={e.options}
                    />
                  </Form.Item>
                );
                break;
              default:
                break;
            }
            return str;
          })}
        </Form>
      </Modal >
    );
  }
}
